<?php

include './meihe/common.php';

header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:GET,POST');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
header('Content-Type: text/html; charset=utf-8');

session_start();

// 检查用户是否登录
if (!$islogin2) {
	exit('{"code":-1,"msg":"请你先登录后再使用！"}');
}

// 获取用户输入数据
$type = $_REQUEST['type'];
$api = $_REQUEST['api'];
$title = daddslashes($_REQUEST['title']);
$sbm = daddslashes($_REQUEST['sbm'] ?? '');
$longurl = $_REQUEST['longurl'];

// 验证 URL 地址
if (empty($longurl)) {
	exit('{"msg":"URL地址不能为空！"}');
} else {
	$longurl = validateUrl($longurl);
}

// 获取域名
$domain = parse_url($longurl, PHP_URL_HOST);


// 检查黑名单
if (!empty($conf['lhbamd'])) {
	if (in_array($domain, explode('|', $conf['lhbamd']))) {
		exit('{"code":-1,"msg":"当前域名已被拉黑，无法生成！"}');
	}
}


// 检查会员状态
$row = $DB->get_row('SELECT * FROM meihe_list WHERE domain=\'' . $domain . '\' limit 1');
if (empty($row)) {
	$domain = get_host($domain);
	$row = $DB->get_row('SELECT * FROM meihe_list WHERE domain=\'' . $domain . '\' and `fhy`=\'2\' limit 1');
	// halt($row);
	if ($row['type'] == 1 && $row['endtime'] <= time()) {
		if ($conf['hydq'] == 1) {
			$DB->query('DELETE FROM meihe_list WHERE domain=\'' . $domain . '\' ');
		}
		exit('{"code":10,"msg":"当前域名会员已到期！请联系站长续费"}');
	}
}

// else {
// 	if ($row['type'] == 1 && $row['endtime'] <= time()) {
// 		if ($conf['hydq'] == 1) {
// 			$DB->query('DELETE FROM meihe_list WHERE domain=\'' . $domain . '\' ');
// 		}
// 		exit('{"code":10,"msg":"当前域名会员已到期！请联系站长续费"}');
// 	}
// }

// 检查自定义标题
if ($title) {
	if ($row['type'] != 1) {
		exit('{"code":2,"msg":"自定义标题只能会员享受！"}');
	}
}

// 检查识别码
if ($sbm) {
	if ($row['type'] != 1) {
		exit('{"code":2,"msg":"自定义识别码只能会员享受！"}');
	}
	if (strlen($sbm) < 6) {
		exit('{"code":2,"msg":"识别码不能低于6位！"}');
	}
}

// 生成短链接
$uid = shorturl($longurl);

// 检查防洪方式
if (!in_array($api, [1, 2, 3])) {
	exit('{"msg":"防洪方式不存在！"}');
}

// 获取防洪方式名称和地址
switch ($api) {
	case 1:
		$fhfsb = '直链方式';
		$fhb = 'api/?';
		break;
	case 2:
		$fhfsb = '跳转方式';
		$fhb = 'api/t.php?';
		break;
	case 3:
		$fhfsb = '缩短方式';
		$fhb = 'api/s.php?';
		break;
}

// 记录生成日志
$DB->query('insert into `meihe_long` (`uid`,`url`) values (\'' . $uid . '\',\'' . $longurl . '\')');

$meihe_api = $DB->get_row("SELECT * FROM `meihe_api` WHERE `sbm`='$type'");
$duanl = $meihe_api['duanl'];

// 返回结果
echo json_encode([
	'code' => 1,
	'msg' => '生成成功！',
	'longurl' => $longurl,
	'shorturl' => $fhb . 'uid=' . $uid,
	'fhfsb' => $fhfsb,
	'haohao_api' => $duanl . $fhb . 'uid=' . $uid,
]);

// 验证 URL 地址的函数
function validateUrl($url)
{
	if (strpos($url, 'http') === false) {
		$url = 'http://' . $url;
	}
	if (!preg_match('/^http[s]?:\\/\\//', $url)) {
		exit('{"msg":"域名格式不正确"}');
	}
	if (!strexists($url, '.')) {
		exit('{"code":-1,"msg":"请您输入正确的域名！"}');
	}
	return $url;
}
